<?php if(!defined('CALL')) exit('No direct script access allowed');

include_once('lib/mysql.class.php');
include_once('lib/utils.class.php');
include_once('lib/logger.class.php');
include_once('models/m_events.class.php');
include_once('cfg/cfg.php');

class mSearch
{
	
	public function __construct()
	{
		self::init();
	}

	public static function init()
	{
		if(is_null(self::$db))
		{
			global $dburl, $def_encoding;
			MySQL::$url = $dburl;
			MySQL::$encoding = $def_encoding;
			self::$db = MySQL::getInstance();
		}
	}

	public static function get_events($str, $actor, $dt_uni = null, $city_id = null)
	{
		self::init();
		
		$results = array();
		if(empty($str)) return $results;
		
		// ищем события начиная с половины года назад
		if($dt_uni == null)
		{
			$curdt = getdate();
			$dt_uni = date("Y-m-d", mktime(0, 0, 0, $curdt['mon'] - 6));
			$dt_uni = date("Y-m-d", mktime(0, 0, 0));
		}
		
		$sql = mEvents::generate_sql($actor->id, null, $city_id, $dt_uni);
		$results = mEvents::read($sql, 0, NUM_ROWS, TRUE, $actor->id, $str);
		return $results;
	}
	
	public static function get_users($str, $limit_num = null, $limit_beg = null)
	{
		self::init();
		
		$results = array();
		if(empty($str)) return $results;
		
		if($limit_num == null)
		{
			$limit = "";
		}
		else
		{
			if($limit_beg == null) $limit_beg = 0;
			$limit = " LIMIT $limit_beg, $limit_num";
		}
		
		$sql =
			"SELECT id ".
			  "FROM users ".
			 "WHERE MATCH(username, note) against('$str')".$limit;
			 
		if(LOG_SQL) Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "SQL: ".$sql);
		$res = self::$db->query($sql);
		while($row = self::$db->fetch_row($res))
			$results[] = $row[0];
		self::$db->free_result($res);
		return $results;
	}
	
	private static $db = null;

}